<?php
namespace app\controllers;


use app\models\Util;
use Yii;
use yii\base\Exception;
use yii\web\Response;
use yii\rest\ActiveController;


/**
 * Created by PhpStorm.
 * @author wangpeng
 * @param Date : 2016/5/18
 * @param Time : 17:32
 * @since 1.0
 */
class Test3Controller extends ActiveController
{
    //初始化类库需要用到的变量,需要直接调用
    public $curl;
    public $toolsClass;
    public $token;
    public $modelClass = 'app\models\Log';
    public function init()
    {
        parent::init();
    }
    public function beforeAction($action)
    {
        //Yii::$app->response->format = Response::FORMAT_JSON;
//        $curlClass=new \curl();
//        $url=Yii::$app->params['OAPI_HOST'].'/gettoken'.'?corpid='.Yii::$app->params['CORPID'].'&corpsecret='.Yii::$app->params['SECRET'];
//        $response=json_decode($curlClass->curl_get(Yii::$app->params['OAPI_HOST'].'/gettoken'.'?corpid='.Yii::$app->params['CORPID'].'&corpsecret='.Yii::$app->params['SECRET']));
//        //$response = Http::get('/gettoken', array('corpid' =>Yii::$app->params['CORPID'], 'corpsecret' =>Yii::$app->params['SECRET'] ));
//        return $this->token = $response->access_token;
        return true;
    }
    //签名
    public $signature = "Signature";
    //Consumer ID
    public $consumerid = "ConsumerID";
    public $producerid = "ProducerID";
    //阿里云身份验证码
    public $aks = "AccessKey";
    //访问码
    public $ak = "AccessKey";
    public $config = array(
        'Topic' => 'shaowei',
        'URL' => 'http://publictest-rest.ons.aliyun.com',
        'Ak' =>'7Du8WjAmnN6UHfhX',
        'Sk' => 'h3K0FbziSjIh2m8ctrZIQWYIlvndkR',
        'ProducerID' => 'PID-shaowei',
        'ConsumerID' =>'CID-shaowei'
    );
    /**
     * 接收消息
     * @author
     * @access  public
     * @since   1.0
     */
    public function actionProcess()
    {
        $toolsClass=new \tools();
        //打印配置信息
        var_dump($this->config);
        //获取Topic
        $topic = $this->config["Topic"];
        //获取Topic的URL路径
        $url =  $this->config["URL"];
        //阿里云身份验证码
        $ak =  $this->config["Ak"];
        //阿里云身份验证密钥
        $sk =  $this->config["Sk"];
        //Consumer ID
        $cid =  $this->config["ConsumerID"];
        $newline = "\n";
        //构造工具对象
        $util = new Util();
        $I=0;
        while (true)
        {
            try
            {
                //构造时间戳
                $date = time()*1000;
                //签名字符串
                $signString = $topic.$newline.$cid.$newline.$date;
                //计算签名
                $sign = $util->calSignatue($signString,$sk);
                //构造签名标记
                $signFlag = $this->signature.":".$sign;
                //构造密钥标记
                $akFlag = $this->ak.":".$ak;
                //标记
                $consumerFlag = $this->consumerid.":".$cid;
                //构造HTTP请求发送内容类型标记
                $contentFlag = "Content-Type:text/html;charset=UTF-8";
                //构造HTTP头部信息
                $headers = array(
                    $signFlag,
                    $akFlag,
                    $consumerFlag,
                    $contentFlag,
                );
                //构造HTTP请求URL
                $getUrl = $url."/message/?topic=".$topic."&time=".$date."&num=32";
                // echo $getUrl.$newline;
                //初始化网络通信模块
                $ch = curl_init();
                //填充HTTP头部信息
                curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
                //设置HTTP请求类型,此处为GET
                curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"GET");
                //设置HTTP请求URL
                curl_setopt($ch,CURLOPT_URL,$getUrl);
                //构造执行环境
                ob_start();
                //开始发送HTTP请求
                curl_exec($ch);
                //获取请求应答消息
                $result = ob_get_contents();
                //清理执行环境
                ob_end_clean();
                //打印请求应答信息
                var_dump($result);

                //关闭HTTP网络连接
                curl_close($ch);
                //解析HTTP应答信息
                $messages= json_decode($result,true);
                //如果应答信息中的没有包含任何的Topic信息,则直接跳过
                if (count($messages) ==0)
                {
                    continue;
                }

                //依次遍历每个Topic消息
                foreach ((array)$messages as $message)
                {
                    var_dump($messages);
                    var_dump($message);
                    $body=json_decode($message['body'],true);
                    //echo $body['content'];
                    $date1= date('Y-m-d H:i:s',$body['time']);
                    $url123='http://dingtalkapi.vguang.com/ding/user-auto/test2?content='.$body['content'].'&time='.$date1.'&id='.$message['key'];
                    echo $url123;
                    //发送
//                    echo $url;
//                    if($body)
                    $this->vget($url123);

//                    die();
                    //获取时间戳
                    $date = (int)($util->microtime_float()*1000);
                    //构造删除Topic消息URL
                    $delUrl = $url."/message/?msgHandle=".$message['msgHandle']."&topic=".$topic."&time=".$date;
                    // echo $delUrl.$newline;
                    //签名字符串
                    $signString = $topic.$newline.$cid.$newline.$message['msgHandle'].$newline.$date;
                    //计算签名
                    $sign = $util->calSignatue($signString,$sk);
                    //构造签名标记
                    $signFlag = $this->signature.":".$sign;
                    //构造密钥标记
                    $akFlag = $this->ak.":".$ak;
                    //构造消费者组标记
                    $consumerFlag = $this->consumerid.":".$cid;
                    //构造HTTP请求头部信息
                    $delheaders = array(
                        $signFlag,
                        $akFlag,
                        $consumerFlag,
                        $contentFlag,
                    );
                    //初始化网络通信模块
                    $ch = curl_init();
                    //填充HTTP请求头部信息
                    curl_setopt($ch,CURLOPT_HTTPHEADER,$delheaders);
                    //设置HTTP请求URL信息
                    curl_setopt($ch,CURLOPT_URL,$delUrl);
                    //设置HTTP请求类型,此处为DELETE
                    curl_setopt($ch,CURLOPT_CUSTOMREQUEST,'DELETE');
                    //构造执行环境
                    ob_start();
                    //开始发送HTTP请求
                    $tmpInfo=curl_exec($ch);
                    //获取请求应答消息
                    $result = ob_get_contents();
                    //清理执行环境
                    ob_end_clean();
//                    var_dump($tmpInfo);
//                    var_dump($delUrl);
//                    var_dump($delheaders);
//                    //打印应答消息
                    var_dump($result);
                    //关闭连接
                    curl_close($ch);
                }
            }
            catch (Exception $e)
            {
                //打印异常信息
                echo $e->getMessage();
            }
        }
    }

    public function actionProducer($k)
    {
        $key=array('03173118413709','03173062148843','03173118413709');
        $K=array('A','B','C');
        for($i=0;$i<3;$i++){

            $this->Producer($k.$K[$i],$key[$i]);

        }
    }
    /** //发布消息流程
     *
     * @author  LiShaoWei
     * @access  public
     * @since   1.0
     */

    public function Producer($k,$key)
    {
        //打印配置信息

        //打印配置信息
        var_dump($this->config);
        //获取Topic
        $topic = $this->config["Topic"];
        //获取Topic的URL路径
        $url =  $this->config["URL"];
        //阿里云身份验证码
        $ak =  $this->config["Ak"];
        //阿里云身份验证密钥
        $sk =  $this->config["Sk"];
        //Consumer ID
        $pid =  $this->config["ProducerID"];
        //HTTP请求体内容
        $body = json_encode(array(
            'content'=>$k,
            'time'=>time()
        ));
        $newline = "\n";
        //构造工具对象
        $util = new Util();
//        for ($i = 0; $i<500; $i++) {
        //计算时间戳
        $date = time()*1000;
        //POST请求url
        $postUrl = $url."/message/?topic=".$topic."&time=".$date."&tag=lishaowei&key=".$key;
        //签名字符串
        $signString = $topic.$newline.$pid.$newline.$this->md5($body).$newline.$date;
        //计算签名
        $sign = $util->calSignatue($signString,$sk);
        //初始化网络通信模块
        $ch = curl_init();
        //构造签名标记
        $signFlag = $this->signature.":".$sign;
        //构造密钥标记
        $akFlag = $this->aks.":".$ak;
        //标记
        $producerFlag = $this->producerid.":".$pid;
        //构造HTTP请求头部内容类型标记
        $contentFlag = "Content-Type:text/html;charset=UTF-8";
        //构造HTTP请求头部
        $headers = array(
            $signFlag,
            $akFlag,
            $producerFlag,
            $contentFlag,
        );
        //设置HTTP头部内容
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        //设置HTTP请求类型,此处为POST
        curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
        //设置HTTP请求的URL
        curl_setopt($ch,CURLOPT_URL,$postUrl);
        //设置HTTP请求的body
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        //构造执行环境
        ob_start();
        //开始发送HTTP请求
        curl_exec($ch);
        //获取请求应答消息
        $result = ob_get_contents();
        //清理执行环境
        ob_end_clean();
        //打印请求应答结果
        var_dump($result);
        //关闭连接
        curl_close($ch);
    }
    //计算md5
    private function md5($str)
    {
        return md5($str);
    }

    function vget ( $url , $ucookie='' )
    { // 模拟登录获取Cookie函数

        $curl = curl_init (); // 启动一个CURL会话
        curl_setopt ( $curl , CURLOPT_URL , $url ); // 要访问的地址
        curl_setopt ( $curl , CURLOPT_SSL_VERIFYPEER , 0 ); // 对认证证书来源的检查
        curl_setopt ( $curl , CURLOPT_SSL_VERIFYHOST , 2 ); // 从证书中检查SSL加密算法是否存在
        //curl_setopt ( $curl , CURLOPT_USERAGENT , $_SERVER['HTTP_USER_AGENT'] ); // 模拟用户使用的浏览器
        curl_setopt ( $curl , CURLOPT_FOLLOWLOCATION , 1 ); // 使用自动跳转
        curl_setopt ( $curl , CURLOPT_AUTOREFERER , 1 ); // 自动设置Referer
        // curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt ( $curl , CURLOPT_COOKIEJAR , $ucookie ); // 存放Cookie信息的文件名称
        curl_setopt ( $curl , CURLOPT_COOKIEFILE , $ucookie ); // 读取上面所储存的Cookie信息
        curl_setopt ( $curl , CURLOPT_TIMEOUT , 30 ); // 设置超时限制防止死循环
        curl_setopt ( $curl , CURLOPT_HEADER , 0 ); // 显示返回的Header区域内容
        curl_setopt ( $curl , CURLOPT_RETURNTRANSFER , 1 ); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec ( $curl ); // 执行操作
        if (curl_errno ( $curl )) {
            echo 'Errno' . curl_error ( $curl );
        }
        curl_close ( $curl ); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }
}